﻿using System;
using System.Collections;
using System.Configuration;
using System.Collections.Specialized;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.ComponentModel;
using ESRI.ArcGIS.ADF.Web;
using ESRI.ArcGIS.ADF.Web.UI.WebControls;
using ESRI.ArcGIS.ADF.Web.DataSources;
using ESRI.ArcGIS.ADF.Web.Geometry;

public enum ZoomToScaleMapUnit
{
    Resource_Default, DecimalDegrees, Feet, Meters
}


public partial class ZoomToScale : System.Web.UI.UserControl
{
    MapResourceManager m_resourceManger;
    private string m_mapId = "Map1";
    private Map m_map;
    private string m_scriptUrl = "ZoomToScale/ZoomToScale.js";
    private ZoomToScaleMapUnit m_DefaultMapUnits = ZoomToScaleMapUnit.DecimalDegrees; // fallback value used if resource value is not available
    private ZoomToScaleMapUnit m_mapUnits;
    private ZoomToScaleMapUnit m_startMapUnits = ZoomToScaleMapUnit.Resource_Default;

    protected void Page_Load(object sender, EventArgs e)
    {
        // find the map control
        if (m_mapId == null || m_mapId.Length == 0) m_mapId = "Map1";
        m_map = Page.FindControl(m_mapId) as Map;
        // find the map resource manager
        m_resourceManger = Page.FindControl(m_map.MapResourceManager) as MapResourceManager;

    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (!m_map.IsAsync)
        {
            if (m_startMapUnits == ZoomToScaleMapUnit.Resource_Default)
                m_mapUnits = GetResourceDefaultMapUnit();
            else
                m_mapUnits = m_startMapUnits;
            StringBuilder sb = new StringBuilder();
            StringBuilder sb2 = new StringBuilder();
            TilingScheme scheme = m_map.GetTilingScheme(m_map.PrimaryMapResource);
            if (scheme != null)
            {
                int levels = scheme.TileCacheInfo.LodInfos.Length;
                for (int i = 0; i < levels; i++)
                {
                    if (i > 0) sb2.Append(",");
                    sb2.AppendFormat("'{0}'", scheme.TileCacheInfo.LodInfos[i].Scale);
                }
            }
            if (!Page.ClientScript.IsStartupScriptRegistered("zoomToScaleScript"))
            {
                string script = String.Format("\n<script language='javascript' type='text/javascript' src='{0}'></script>\n", m_scriptUrl);
                Page.ClientScript.RegisterStartupScript(typeof(Page), "zoomToScaleScript", script);
            }

            if (!Page.ClientScript.IsStartupScriptRegistered(ClientID + "_InitScript"))
            {
                string initScript = @"
                                Sys.Application.add_init(function() 
                                {{ 
                                    $create(ADF.Samples.zoomScaleClass,{{'scales': [{0}] , 'units': '{1}'}},null,{{'map':'{2}'}},$get('{3}'));
                                }});
                                ";

                initScript = String.Format(initScript, sb2.ToString(), m_mapUnits.ToString(), m_mapId, ClientID);
                Page.ClientScript.RegisterStartupScript(typeof(Page), ClientID + "_InitScript", initScript, true);
            }
        }
    }


    #region Action Methods

    private ZoomToScaleMapUnit GetResourceDefaultMapUnit()
    {
        #region Get map units
        Units mu = Units.DecimalDegrees;
        // use the primary resouce, if defined
        string primeResource = m_map.PrimaryMapResource;

        IGISResource resource = null;
        try
        {
            if (!String.IsNullOrEmpty(primeResource))
                resource = m_resourceManger.GetResource(primeResource);
            else
                resource = m_resourceManger.GetResource(0);
            IMapFunctionality mapFunctionality = null;
            try
            {
                if (resource != null)
                    mapFunctionality = (IMapFunctionality)resource.CreateFunctionality(typeof(IMapFunctionality), "mapFunctionality");
                if (mapFunctionality != null && mapFunctionality.Supports("Units"))
                    mu = mapFunctionality.Units;
            }
            finally
            {
                if (mapFunctionality != null)
                    mapFunctionality.Dispose();
            }
        }
        finally
        {
            if (resource != null)
                resource.Dispose();
        }
        #endregion

        #region Get ZoomToScale Units
        ZoomToScaleMapUnit mUnit = m_DefaultMapUnits;
        try
        {
            if (mu == Units.DecimalDegrees)
                mUnit = ZoomToScaleMapUnit.DecimalDegrees;
            else if (mu == Units.Feet)
                mUnit = ZoomToScaleMapUnit.Feet;
            else if (mu == Units.Meters)
                mUnit = ZoomToScaleMapUnit.Meters;

        }
        catch
        {
            // cannot get units from resource... default to fallback value set in declaration
            mUnit = m_DefaultMapUnits;
        }
        #endregion

        return mUnit;
    }

    #endregion

    #region Properties

    private MapResourceManager MapResourceManager
    {
        get { return m_resourceManger; }
        set { m_resourceManger = value; }
    }

    /// <summary>
    /// Id of Buddy MapControl
    /// </summary>
    [DefaultValue("Map1")]
    [Description("ID of Map Control")]
    public string Map
    {
        get { return m_mapId; }
        set { m_mapId = value; }
    }


    /// <summary>
    /// Unit used resource. Resource_Default will return value from resource, if available. Other values will force calculations to use that unit.
    /// </summary>
    [Description("Type of unit used by map.")]
    [DefaultValue(ZoomToScaleMapUnit.Resource_Default)]
    public ZoomToScaleMapUnit MapUnits
    {
        get { return m_startMapUnits; }
        set { m_startMapUnits = value; }
    }

    /// <summary>
    /// Path to javascript file
    /// </summary>
    [DefaultValue("ZoomToScale.js")]
    [Description("Url of javascript file")]
    public string ScriptUrl
    {
        get { return m_scriptUrl; }
        set { m_scriptUrl = value; }
    }

    #region Non-Browsable Properties
    [Browsable(false)]
    public override bool Visible
    {
        get { return base.Visible; }
        set { base.Visible = value; }
    }

    [Browsable(false)]
    public override bool EnableTheming
    {
        get { return base.EnableTheming; }
        set { base.EnableTheming = value; }
    }

    [Browsable(false)]
    public override bool EnableViewState
    {
        get { return base.EnableViewState; }
        set { base.EnableViewState = value; }
    }
    #endregion

    #endregion

}
